package org.usmile.algorithms.huawei.acm;

import java.util.*;

// https://blog.csdn.net/qfc_128220/article/details/128500984
public class _人数最多的站点 {


    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] ranges = new int[n][2];
        int maxEnd = 0;
        for (int i = 0; i < n; i++) {
            ranges[i][0] = sc.nextInt();
            ranges[i][1] = sc.nextInt();
            maxEnd = Math.max(maxEnd, Math.max(ranges[i][0], ranges[i][1]));
        }

        System.out.println(getResult(ranges, maxEnd));
    }

    public static int getResult(int[][] ranges, int maxEnd) {
        // 如果存在 [3,2] 这种坐车区间，即从站点3 -> 站点4 -> 站点1 -> 站点2，则此时将该坐车区间拆分为 [3, 4]和[1, 2]
        ArrayList<Integer[]> tmp = new ArrayList<>();
        for (int[] range : ranges) {
            int start = range[0];
            int end = range[1];

            if (start > end) {
                tmp.add(new Integer[]{start, maxEnd});
                tmp.add(new Integer[]{1, end});
            } else {
                tmp.add(new Integer[]{start, end});
            }
        }

        // 最大重叠区间个数求解
        tmp.sort(Comparator.comparingInt(a -> a[0]));
        PriorityQueue<Integer> heap = new PriorityQueue<>();
        int max = 0;
        int maxStop = -1;
        for (Integer[] range : tmp) {
            int start = range[0];
            int end = range[1];
            while (heap.size() > 0 && start > heap.peek()) {
                heap.poll();
            }
            heap.offer(end);
            if (heap.size() > max) {
                max = heap.size();
                maxStop = start;
            }
        }

        return maxStop;
    }
}
